#include <stdint.h>
#include "Circle_buffer.h"
#include "stdio.h"


//初始化环形缓冲区 
void circle_buf_init(p_circle_buf pCircleBuf, uint32_t len, uint8_t *buf)
{
	pCircleBuf->r = pCircleBuf->w = 0;
	pCircleBuf->len = len;
	pCircleBuf->buf = buf;
}

//从环形缓冲区读取数据 
//每读取一个字节r标志位+1
int circle_buf_read(p_circle_buf pCircleBuf, uint8_t *pVal)
{
	if (pCircleBuf->r != pCircleBuf->w)
	{
		*pVal = pCircleBuf->buf[pCircleBuf->r];
		
		pCircleBuf->r++;
		
		if (pCircleBuf->r == pCircleBuf->len)
			pCircleBuf->r = 0;
		return 0;
	}
	else
	{
		return -1;
	}
}

//向环形缓冲区写入数据 
//写入取一个字节w标志位+1
int circle_buf_write(p_circle_buf pCircleBuf, uint8_t val)
{
	uint32_t next_w;
	
	next_w = pCircleBuf->w + 1;
	if (next_w == pCircleBuf->len)
		next_w = 0;
	
	// 打印调试信息
  //printf("Before Write - r: %u, w: %u, next_w: %u, len: %u\n", pCircleBuf->r, pCircleBuf->w, next_w, pCircleBuf->len);

	if (next_w != pCircleBuf->r)
	{
		pCircleBuf->buf[pCircleBuf->w] = val;
		pCircleBuf->w = next_w;
		
		// 打印调试信息
    //printf("After Write - r: %u, w: %u, len: %u\n", pCircleBuf->r, pCircleBuf->w, pCircleBuf->len);
		return 0;
	}
	else
	{
		return -1;
	}
}

//int circle_buf_is_empty(p_circle_buf pBuf) {
//    return pBuf->r == pBuf->w;
//}

//int circle_buf_is_full(p_circle_buf pBuf) {
//    uint32_t next_w = pBuf->w + 1;
//    if (next_w == pBuf->len)
//        next_w = 0;
//    return next_w == pBuf->r;
//}

//uint32_t circle_buf_available(p_circle_buf pBuf) {
//    if (pBuf->w >= pBuf->r)
//        return pBuf->w - pBuf->r;
//    return pBuf->len - (pBuf->r - pBuf->w);
//}

